package gen

import (
	"fmt"
	"strings"
)

type ClassBlock struct {
	CodeBlock
	//文件输出目录
	FileDir string
	//文件名
	FileName string
	//文件是否缺失时才生成
	GenIfAbsent bool
}

func (c *ClassBlock) BuildResult() string {
	build0(c)
	var result string
	for _, v := range c.builder {
		result += "\n" + v
	}
	return result
}

func (c *ClassBlock) Build() {
	build0(c)
	var result string
	for _, v := range c.builder {
		result += "\n" + v
	}
	fmt.Println("result => ", result)
}

func (c *ClassBlock) checkStep(trimLine string) {

}

func (c *ClassBlock) isEnd() bool {
	return false
}

func OfClassBlock(head string) *ClassBlock {
	parts := strings.Split(head, " ")
	var block ClassBlock
	block.Head = head
	block.FileDir = ParseFromExpression(parts[1])
	block.FileName = ParseFromExpression(parts[2])
	for _, v := range parts {
		if v == "ifAbsent" {
			block.GenIfAbsent = true
		}
	}
	return &block
}

func NewClassBlock(lines []string) []*ClassBlock {
	var blocks []*ClassBlock
	var currBlock *ClassBlock
	for _, v := range lines {
		if currBlock != nil {
			if v == "#class end" {
				blocks = append(blocks, currBlock)
				currBlock = nil
				continue
			}
			currBlock.addLine(v)
		} else {
			if strings.HasPrefix(v, "#format") {
				formatter := FormatterOf(v)
				FormatMap[formatter.RawType] = formatter
			} else if strings.HasPrefix(v, "#wrapper") {
				parts := strings.Split(v, " ")
				WrapperMap[parts[1]] = parts[2]
			} else if strings.HasPrefix(v, "#list") {
				List = ListPatternOf(v)
			} else if strings.HasPrefix(v, "#arg") {
				parts := strings.Split(v, " ")
				_, ok := Params[parts[1]]
				if !ok {
					fmt.Println("未找到参数：", parts[1])
				}
			} else if strings.HasPrefix(v, "#class") {
				currBlock = OfClassBlock(v)
			}
		}
	}
	return blocks
}

func (c *ClassBlock) addLineExpression(lineExpression string) {
	c.builder = append(c.builder, ParseFromExpression(lineExpression))
}

func (c *ClassBlock) GetDesc() string {
	return "ClassBlock at " + c.Head
}
